<template>
  <div class="container">
    <div class="sidebar">
      <!-- <el-tree :data="surfdata" :props="dPs"  @node-click="handleNodeClick" default-expand-all :highlight-current="highlightBd" node-key="id" :current-node-key='currentKey' ref="treeRef"></el-tree> -->
      <el-dropdown  @command="handleCommand">
        <el-button style="margin-top: 10px; margin-left:10px">
          传感器<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" >
          <el-dropdown-item v-for="item in deviceList.slice(0,2)" :key="item.value" :command="item">
            {{ item.name.slice(2) }}
          </el-dropdown-item>
          <!-- <el-dropdown-item>狮子头</el-dropdown-item>
          <el-dropdown-item>螺蛳粉</el-dropdown-item>
          <el-dropdown-item disabled>双皮奶</el-dropdown-item>
          <el-dropdown-item divided>蚵仔煎</el-dropdown-item> -->
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="content">
      <!-- activeName -->
      <el-tabs v-model="activeName"  @tab-click="handleClick">
        <!-- <el-button @click="getList"> get</el-button> -->
      
        <el-tab-pane :label="`数据图 ${choseDeviceName}`" name="first">
          <div class="chart-container">
            <!-- <chart v-loading="loading" height="33%" width="100%" :chartData="chartData" :chartRiqi="chartRiqi"  :titleText="titleText"/>
            <chart v-loading="loading" height="33%" width="100%" :chartData="chatData2" :chartRiqi="chartRiqi2" :id="idMiddle" :titleText="titleText2"/>
            <chart v-loading="loading" height="33%" width="100%" :chartData="chatData3" :chartRiqi="chartRiqi3" :id="idBottom" :titleText="titleText3"/> -->
            <chart v-loading="loading" height="33%" width="100%" :chartData="chartData" :chartRiqi="chartRiqi"  id="top" :titleText="titleText"/>
            <chart v-loading="loading" height="33%" width="100%" :chartData="chartData2" :chartRiqi="chartRiqi2" id="middle" :titleText="titleText2"/>
            <chart v-loading="loading" height="33%" width="100%" :chartData="chartData3" :chartRiqi="chartRiqi3" id="bottom" :titleText="titleText3"/>
            <!-- <chart v-loading="loading" height="33%" width="100%" :chartData="chartData2" :chartRiqi="chartRiqi2" :id="idMiddle"/>
            <chart v-loading="loading" height="33%" width="100%" :chartData="chartData3" :chartRiqi="chartRiqi3" :id="idBottom"/> -->
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane label="泥位波动图" name="second"></el-tab-pane> -->
        <!-- <el-tab-pane label="刨面内侧点缩略图" name="third"></el-tab-pane> -->
      </el-tabs>
    </div>
    
    
  </div>
</template>

<script>
import chart from '../../components/charts/Mix-rain.vue'
// import chart from '../../components/charts/Mix-rain.vue'
// import chart from '../../components/charts/Mix-rain.vue'
import { getDeviceSurfData, listDevice , listkafkaData, sensorPointList, listmoveDevice } from "@/api/screen/device";

export default {
  name: 'graph',
  components: { chart },
  data() {
    return {
        choseDeviceName:'',
        currentKey: 0,
        highlightBd: true,
        activeName: 'first',
        chartData: [
        0.053935,
0.065041,
1.912789,
0.053935,
-0.33312,
0.065041,
-0.33312,
0.053935,
-0.185802,
-0.185802,




        ],
        chartData2: [
        -2.156929,
-2.407705,
3.634539,
-2.156929,
-2.798523,
-2.407705,
-2.798523,
-2.156929,
-2.396126,
-2.396126,



        ],
        chartData3: [
        1.413015,
3.480818,
6.429768,
1.413015,
2.12942,
3.480818,
2.12942,
1.413015,
3.520459,
3.520459,



        ],
        chartRiqi: [
          '2024-12-4 9:00:00', '2024-12-4 9:00:05', '2024-12-4 9:00:10', '2024-12-4 9:00:10', '2024-12-4 9:00:15', '2024-12-4 9:00:15', '2024-12-4 9:00:20'
        ],
        idTop:'top',
        idMiddle: 'middle',
        idBottom: 'bottom',
        chartRiqi2: [
          
        '2024-12-4 9:00:00', '2024-12-4 9:00:05', '2024-12-4 9:00:10', '2024-12-4 9:00:10', '2024-12-4 9:00:15', '2024-12-4 9:00:15', '2024-12-4 9:00:20'
        ],
        chartRiqi3: [
          `2024-12-4 9:00:00`, '2024-12-4 9:00:05', '2024-12-4 9:00:10', '2024-12-4 9:00:10', '2024-12-4 9:00:15', '2024-12-4 9:00:15', '2024-12-4 9:00:20'
        ],
        // chartRiqi3: [],
        titleText: 'dE-东(mm)',
        titleText2: 'dN-北(mm)',
        titleText3: 'dU-高(mm)',
        // titleText3: this.getCurrentTime(),

        devicesurfDataList: [],
        surfdata: [],
        activeName: 'first',
        deviceList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        elTreeData: [],
        loading: true,
        currentdate: this.getCurrentTime(),
        picTime: ''
      }
  },
  computed: {
    dPs() {
      return {
        children: 'children',
        label: 'label'
      };
    },
    chartRiqi3() {
      return [`${this.picTime} 9:00:00`, '2024-12-4 9:00:05', '2024-12-4 9:00:10', '2024-12-4 9:00:10', '2024-12-4 9:00:15', '2024-12-4 9:00:15', '2024-12-4 9:00:20']
    }
  },
  created() {
    // console.log('this.picTime', this.picTime, typeof(this.picTime))
    // this.chartRiqi3 = [`${this.picTime} 9:00:00`, '2024-12-4 9:00:05', '2024-12-4 9:00:10', '2024-12-4 9:00:10', '2024-12-4 9:00:15', '2024-12-4 9:00:15', '2024-12-4 9:00:20']
  },
    // this.getList()
    // this.getlistkafkaDevice()
  mounted() {
    // this.getList()
    // this.getlistkafkaDevice()
    this.username = this.$store.state.user.name
    // this.chartRiqi3 = [`${this.picTime} 9:00:00`, '2024-12-4 9:00:05', '2024-12-4 9:00:10', '2024-12-4 9:00:10', '2024-12-4 9:00:15', '2024-12-4 9:00:15', '2024-12-4 9:00:20']

    if(this.username == 'maguan') {
        this.getsensorPoint('马关')
      }
      else if (this.username == 'guanxi'){
        this.getsensorPoint('关西')
      }
      else {
        this.getsensorPoint()
      }
  },
  methods: {
    getCurrentTime() {
        //获取当前时间并打印
  　　let yy = new Date().getFullYear();
  　　let mm = new Date().getMonth()+1;
  　　let dd = new Date().getDate();
  　　let hh = new Date().getHours();
  　　let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
  　　let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
  // 　　let gettime = yy+'/'+mm+'/'+dd+' '+hh+':'+mf+':'+ss;
  　　let gettime = yy+'-'+mm+'-'+dd;
  　　this.picTime = gettime
  　　return gettime
    },

    handleCommand(command) {
      console.log('command', command)
      this.choseDeviceName = command.name
      listkafkaData({devicecode: command.strId, isAsc: 'desc', orderByColumn: 'epoch', pageSize: 100}).then(response => {
      console.log('deviceLevelDataList',response.rows) 
      this.loading = false
      // let resList = response.rows
      // this.deviceLevelDataList = resList.reverse()
      this.deviceLevelDataList = response.rows
      this.chartData = this.deviceLevelDataList.map(item=> {return item.gpstotale})
      this.chartRiqi = this.deviceLevelDataList.map(item=> {return item.epoch})

      console.log('this.chartRiqi', this.chartRiqi)
      
      this.chartData2 = this.deviceLevelDataList.map(item=> {return item.gpstotaln})
      this.chartRiqi2 = this.deviceLevelDataList.map(item=> {return item.epoch})

      this.chartData3 = this.deviceLevelDataList.map(item=> {return item.gpstotalu})
      this.chartRiqi3 = this.deviceLevelDataList.map(item=> {return item.epoch})


        console.log('this.chartData', this.chartData)
        }
      );
    },
    //站点列表
    getsensorPoint(e) {
      listmoveDevice({NAME: e, sensorName: ''}).then(response=> {
          this.deviceList = response.rows
          console.log('deviceListDam',this.deviceList) 
          // this.convertToElTree()
          // this.groupByDeviceId()
          // 选择并处理第一个树节点
          // if (this.deviceList?.length > 0 && this.deviceList[0].children && this.deviceList[0].children?.length > 0) {
          //   const firstNodeId = this.deviceList[0].children[0].id;
          //   this.handleNodeClick({id: firstNodeId});
          // }

          console.log('this.deviceList', this.deviceList)
          // monitordevicecode 所属监测点
          // monitordevicename 设备类型
          // deviceid  设备id
          this.total = response.total;
          this.loading = false;

        })
      },
    handleClick (tab, event) {
      console.log(tab, event)
    },
    getlistkafkaDevice() {
      listkafkaDevice().then(response => {
        console.log('kafkadata', response.rows)
      })
      },
     /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice({monitorDeviceName:'表面位移'}).then(response => {
          console.log('deviceList-damdata',response.rows) 
          this.deviceList = response.rows
          this.groupByDeviceId()

          // 选择并处理第一个树节点
          if (this.surfdata?.length > 0 && this.surfdata[0].children && this.surfdata[0].children?.length > 0) {
            // const firstNodeId = this.damdata[0].children[0].id;
            const firstNodeId = this.deviceList.reverse()[0].id
            this.handleNodeClick({id: firstNodeId});
          }
          // this.convertToElTree()
          console.log('this.deviceList', this.deviceList)
          // monitordevicecode 所属监测点
          // monitordevicename 设备类型
          // deviceid  设备id
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 函数根据 deviceId 对设备进行分组
    groupByDeviceId(devices = this.deviceList) {
        return devices.reduce((groups, device) => {
          const { deviceId } = device;
          if (!groups[deviceId]) {
            groups[deviceId] = [];
          }
          groups[deviceId].push({
            label: device.deviceName,
            ...device
          });
          console.log('groups', groups)
          this.groupedDevices = groups


          // 将分组转换为 el-tree 的数据格式（每个分组一个树）
          this.surfdata = Object.keys(this.groupedDevices).map(deviceId => {
            return {
              label: `位置编号 ${deviceId}`,
              children: this.groupedDevices[deviceId]
              // children: this.groupedDevices[{ id: device.deviceId, label: device.deviceName  }]
            };
          });
          return groups;
        }, {});
      },
    /** 查询位移数据详情 */
    // getDeviceSurfData(e) {
    //   this.loading = true;
    //   getDeviceSurfData({deviceId:e, isAsc:'desc', orderByColumn:'createTime'}).then(response => {
    //     console.log('devicesurfDataList',response.rows) 
    //     this.loading = false
    //     // let resList = response.rows
    //     // this.devicesurfDataList = resList.reverse()
    //     this.devicesurfDataList = response.rows
    //     this.chartRiqi = this.devicesurfDataList.map(item=> {return item.createTime})
    //     this.chartRiqi2 = this.devicesurfDataList.map(item=> {return item.createTime})
    //     this.chartRiqi3 = this.devicesurfDataList.map(item=> {return item.createTime})
    //     this.chartData = this.devicesurfDataList.map(item=> {return item.tag})
    //     this.chatData2 = this.devicesurfDataList.map(item=> {return item.tag})
    //     this.chatData3 = this.devicesurfDataList.map(item=> {return item.tag})
    //     console.log('this.chartData', this.chartData, this.chartRiqi)
    //     }
    //   );
    // },
    handleNodeClick(surfdata) {
      console.log(surfdata, surfdata.id);
      if( surfdata.id == null) {
        console.log('null')
      } else {
        this.getDeviceSurfData(surfdata.deviceId)
        console.log('surfdata.id', surfdata.id)
        this.currentKey = surfdata.deviceId
        this.$nextTick(() => {
          this.$refs['treeRef'].setCurrentKey(this.currentKey)
        })
      }
    },
    convertToElTree(e = this.deviceList) {
        const tempMap = new Map(); // 临时 Map 用于合并相同项
        // 遍历设备列表
        e.forEach(device => {
          if (tempMap.has(device.monitorDeviceCode) || tempMap.has(device.monitorDeviceName)) {
             // 如果存在相同设备名称的项，则合并
             const existingDevice = tempMap.get(device.monitorDeviceCode);
            //  const existingMonitordevicename = tempMap.get(device.monitordevicename);
             existingDevice.children.push({ id: device.deviceId, label: device.deviceName });
          } else {
             // 如果不存在相同设备名称的项，则创建新节点
             tempMap.set(device.monitorDeviceCode, {
              label: device.monitorDeviceCode,
              children: [{ id: device.deviceId, label: device.deviceName  }]
            });
            // 如果不存在相同设备名称的项，则创建新节点
            
          }
        });
        
        // 将 Map 转换为数组，存储到 elTreeData 中
        this.elTreeData = Array.from(tempMap.values());

        this.surfdata = this.elTreeData
        console.log('this.elTreeData', this.elTreeData)
      }
  }
}
</script>

<style  lang="scss">
.container .sidebar {
  // 修改高亮背景色和color
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    // background-color: #fcf5f3;
    color: #409eff;
  }
  // .el-tree-node:focus > .el-tree-node__content {
  //   color:  #409eff;
  //   /* transition: background 1s; */
  // }
}


.el-tree-node:focus > .el-tree-node__content {
  color:  #409eff;
  /* transition: background 1s; */
}

.container {
  display: flex;
}

  
.sidebar {
  width: 200px; /* Adjust the width as per your layout */
  height: 100vh;
}

.content {
  flex: 1;
  height: 100vh;
}


.chart-container{
position: relative;
width: 100%;
height: 80vh;
}

.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}

</style>